package com.heima.search.interceptor;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.WmThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AppTokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if (userId==null){
            response.setCharacterEncoding("Utf-8");
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);//401
            response.getWriter().write(JSON.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH)));
            return false;
        }
        WmThreadLocalUtil.set(Long.valueOf(userId));
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocalUtil.remove();
        super.postHandle(request, response, handler, modelAndView);
    }
}
